﻿using System;
using System.Collections.Generic;

namespace GLDotNet
{
	public class GLContextListener : IGLContextListener
	{
        bool checkErrors = true;

		public void BeforeNativeFunctionCall(GLContext context, GLNativeFunctions function)
		{
			if (function == GLNativeFunctions.GetError)
				return;

            if (function == GLNativeFunctions.Begin)
                this.checkErrors = false;

            if (this.checkErrors)
            {
                while (context.GetError() != GL.NoError) ;
            }
		}

		public void AfterNativeFunctionCall(GLContext context, GLNativeFunctions function)
		{
			if (function == GLNativeFunctions.GetError)
				return;

            if (this.checkErrors)
            {
                ErrorCode error = context.GetError();

                if (error != GL.NoError)
                {
                    List<string> errors = new List<string>() { error.ToString() };

                    while ((error = context.GetError()) != GL.NoError)
                        errors.Add(error.ToString());

                    throw new GLDotNetException(string.Format("The function {0} returned error(s): {1}.", function, string.Join(", ", errors)));
                }
            }

            if (function == GLNativeFunctions.End)
                this.checkErrors = true;
		}
	}
}
